package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.utils.BaseContext;
import com.reggie.utils.MD5Tools;
import com.reggie.utils.Result;
import com.reggie.pojo.Employee;
import com.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录（密码有md5加密）
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public Result<Employee> login(HttpServletRequest request ,@RequestBody Employee employee) {
        //1.将页面提交的password进行加密
        String password = employee.getPassword();
        password = MD5Tools.convertMD5(password);
        //2.根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());

        Employee emp = employeeService.getOne(wrapper);
        //3.如果没有查询到返回”查无此用户“
        if (emp == null) {
            return Result.error("查无此用户~~");
        }
        //4.密码比对，如果密码不一致返回”密码错误“
        if (!password.equals(emp.getPassword())) {
            return Result.error("密码错误~~");
        }
        //5.查看员工状态，如果为禁用，则返回“员工已被禁用”
        if (emp.getStatus() != 1) {
            return Result.error("员工已被禁用~~");
        }
        //6.登陆成功，将员工id存入Session并返回结果
        request.getSession().setAttribute("employee", emp.getId());

        log.info("登陆成功，员工id:{}",request.getSession().getAttribute("employee"));

        return Result.success(emp);
    }

    /**
     * 员工退出登录
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        //1.清理session信息
        request.getSession().removeAttribute("employee");
        //清理线程中保留的用户id
        BaseContext.removeCurrent();
        //2.返回结果
        return Result.success("退出成功~~");
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @PostMapping
    public Result<String> save(HttpServletRequest request, @RequestBody Employee employee) {
//        log.info("新增员工，员工信息{}",employee.toString());
        //统一给初始密码“123456”，需要MD5加密
        employee.setPassword(MD5Tools.convertMD5("123456"));
        //使用自动填充填充数据
        /*//赋予创建时间
        employee.setCreateTime(LocalDateTime.now());
        //赋予更新时间
        employee.setUpdateTime(LocalDateTime.now());
        //获得当前登录用户的id
        Long empID = (Long) request.getSession().getAttribute("employee");
        //添加操作的用户
        employee.setCreateUser(empID);
        //更新操作的用户
        employee.setUpdateUser(empID);*/
        //调用方法保存
        employeeService.save(employee);

        return Result.success("新增员工成功~~");
    }

    /**
     * 检查用户是否存在
     * @param username
     * @return
     */
    @GetMapping("/checkIfExist/{username}")
    public Result<String> checkIfExist(@PathVariable String username) {
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, username);
        Employee employee = employeeService.getOne(wrapper);
//        log.info(employee.toString());
        if (employee != null) {
            //用户存在
            return Result.error("用户已存在~~");
        }

        return Result.success("用户不存在");
    }

    /**
     * 员工信息：分页、查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page<Employee>> page(int page,int pageSize,String name) {
//        log.info("page:{},pageSize:{},name:{}", page, pageSize, name);
        //构建分页构造器
        Page<Employee> pageInfo = new Page<>(page,pageSize);
        //构建条件构造器
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        wrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件
        wrapper.orderByDesc(Employee::getCreateTime);
        //执行查询
        employeeService.page(pageInfo,wrapper);
        return Result.success(pageInfo);
    }

    /**
     * 根据id更新员工信息操作：可用于修改信息，启用或禁用员工
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public Result<String> update(HttpServletRequest request,@RequestBody Employee employee) {
//        log.info(String.valueOf(employee.getId()));
        //自动转配
        /*//添加更新时间
        employee.setUpdateTime(LocalDateTime.now());
        //添加更新人ID
        long updateEmp = (long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(updateEmp);*/
        //密码加密
        String password = MD5Tools.convertMD5(employee.getPassword());
        employee.setPassword(password);

        //实现更新操作
        employeeService.updateById(employee);
        return Result.success("操作成功！！");
    }

    /**
     * 根据id查询员工信息
     * @param request
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Employee> getById(HttpServletRequest request,@PathVariable long id) {
        //查询到员工
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            //设置更新时间
            employee.setUpdateTime(LocalDateTime.now());
            //设置进行更新操作的用户
            Long emp = (Long) request.getSession().getAttribute("employee");
            employee.setUpdateUser(emp);
            //密码解密
            String password = MD5Tools.convertMD5(employee.getPassword());
            employee.setPassword(password);

            return Result.success(employee);
        }
        return Result.error("没有查询到对应员工信息");
    }

}
